package ULHT.LIG2N1.RC.VO;

import ULHT.LIG2N1.RC.VO.AnswerLogVO;
import java.util.ArrayList;
import java.util.Collections;

/**
 *
 * VO com o log de jogo
 */
public class RoundLogVO {
    
    private final long MILISECONDS_PER_LEVEL = 15000;

    private int roundNumber;
    private int level;
    private ArrayList<AnswerLogVO> respostasCertas = new ArrayList<>();
    private ArrayList<AnswerLogVO> respostasErradas = new ArrayList<>();
    private ArrayList<AnswerLogVO> clientesTimeout = new ArrayList<>();

    public RoundLogVO(int roundNumber) {
        this.roundNumber = roundNumber;
        if (roundNumber > 14) {
            this.level = 4;
        } else if (roundNumber > 9) {
            this.level = 3;
        } else if (roundNumber > 4) {
            this.level = 2;
        } else {
            this.level = 1;
        }
    }

    public void addClientToStackCorrect(String token, String IPAddress, long tempo) {
        respostasCertas.add(new AnswerLogVO(tempo, IPAddress, token));
    }

    public void addClientToStackWrong(String token, String IPAddress, long tempo) {
        respostasErradas.add(new AnswerLogVO(tempo, IPAddress, token));
    }

    public void addClientToStackTimeout(String token, String IPAddress, long tempo) {
        clientesTimeout.add(new AnswerLogVO(tempo, IPAddress, token));
    }

    public void sortCorrectAnswers() {
        Collections.sort(respostasCertas, new AnswerLogVOComparator());
    }

    public void sortAll() {
        Collections.sort(respostasCertas, new AnswerLogVOComparator());
        Collections.sort(respostasErradas, new AnswerLogVOComparator());
    }

    public String getRoundWinnerIPAdress() {
        sortCorrectAnswers();
        return respostasCertas.get(0).getIPAddress();
    }

    public boolean isWinner(String token) {
        sortCorrectAnswers();
        return respostasCertas.get(0).getToken().equals(token);
    }

    public void autoAdd(String token, String IPAdress, long time, boolean isCorrect) {
        // se o nível for o 4 nunca há timeout da resposta
        if (level > 3) {
            if (isCorrect) {
                addClientToStackCorrect(token, IPAdress, time);
            } else {
                addClientToStackWrong(token, IPAdress, time);
            }
        } else {
            // compara o tempo dado com o tempo de timeout (15 * nivel * 1000)
            if (time > (level * MILISECONDS_PER_LEVEL)) {
                addClientToStackTimeout(token, IPAdress, time);
            } else if (isCorrect) {
                addClientToStackCorrect(token, IPAdress, time);
            } else {
                addClientToStackWrong(token, IPAdress, time);
            }
        }
    }
}
